/* A simple server in the internet domain using TCP
   The port number is passed as an argument */
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>





int main(int argc, char *argv[])
{
  int size = 254081;
  int sockfd, newsockfd, portno, clilen;
  struct sockaddr_in serv_addr, cli_addr;
  int n;
  
  if (argc < 2) {
    fprintf(stderr,"ERROR, no port provided\n");
    return 0;
  }
  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if (sockfd < 0) 
    fprintf(stderr,"ERROR opening socket");
  bzero((char *) &serv_addr, sizeof(serv_addr));
  portno = atoi(argv[1]);
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_addr.s_addr = INADDR_ANY;
  serv_addr.sin_port = htons(portno);
  if (bind(sockfd, (struct sockaddr *) &serv_addr,
	   sizeof(serv_addr)) < 0) 
    fprintf(stderr,"ERROR on binding");
  listen(sockfd,5);
  clilen = sizeof(cli_addr);
  
  char *buffer=malloc(size*sizeof(char));
  newsockfd = accept(sockfd, 
		     (struct sockaddr *) &cli_addr, 
		     &clilen);
  if (newsockfd < 0) 
    fprintf(stderr,"ERROR on accept");
  
  
  bzero(buffer,size*sizeof(char));
  char buff[5000];
  int total = 0;
  while(1){
    bzero(buff,5000);
    n = read(newsockfd,buff, 5000);
	     //(total + 5000 <= size)? 5000 : size-total);
    if (n < 0) fprintf(stderr,"ERROR reading from socket");
    if (total+n >= size)
      break;
    memcpy(&buffer[total], buff, n);
    total += n;
  }
  printf("%s\n",buffer);
  FILE * f = fopen("./copie.jpg","wb");
  int wt = fwrite(buffer, 1, size, f);
  printf("wt = %d\n",wt);
  fclose(f);
  
  n = write(newsockfd,"peers 01723b486b1db72d55eff44ef4aaf46c [127.0.0.1:10016]",strlen("peers 5ce2de06b995755c8b29126748ce01a2 [127.0.0.1:10015]"));
  if (n < 0) fprintf(stderr,"ERROR writing to socket");
  free(buffer);
  
  return 0; 
}
